<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  medias
 */

class m_medias_actions_AjaxUploadAction extends m_backoffice_extends_Action
{
    private $errors;
    
	public function execute()
	{
        $this->beginBackSession()->setDisplayLang($this->getRequestParameter("backLang"));

        $folderId = $this->getRequestParameter("docId");
        $lang = $this->getRequestParameter("docLang");

		$folder = $this->getDocumentProvider()->getByUniqueId($folderId, $lang);
		$mediaForm = $this->getRequestParameter("mediaForm");

        if(!is_null($this->getRequestParameter('checkScript')))
        {
            $this->fileExist($folder);
        }

        $formProvider = f_form_Provider::getInstance();

		$formProvider->setDocumentName("ajaxUpload")
		             ->setModuleName("medias");

        $file = $formProvider->getParams();

		if ($formProvider->isValid() && $this->isValid())
		{
            $tabfile = explode('.', $_FILES['Filedata']['name']);
            $nomfile = $tabfile[0];
            $extfi = end($tabfile);

            $fileName = $_FILES['Filedata']['name'];
            $fileName = f_core_Routing::formatStringForUrl($fileName, true);

            $savePath = $this->getDestPath($folder);

            if(!is_dir($savePath))
            {
                mkdir($savePath, 0777, true);
            }

            if(file_exists($savePath.$fileName))
            {
                $media = $this->getDocumentProvider()
                        ->loadDocuments("modules_medias/media")
                        ->isChildOf($folder->getUniqueId())
                        ->whereIsEqual('document_label', $fileName)
                        ->retrieveFirstDocument($lang);
            }
            else
            {
                $media = m_medias_documents_Media::createNew();
            }

            if (move_uploaded_file($_FILES["Filedata"]["tmp_name"], $savePath.$fileName))
            {
                chmod($savePath.$fileName, 0777);

                $fileObj = f_file_File::getInstance($savePath.$fileName);

                $media	->setMime($fileObj->getMimeType())
                        ->setAuthor("pagizer")
                        ->setExt($fileObj->getExtension())
                        ->setLabel($fileName)
                        ->setAlt($fileObj->getFileName())
                        ->setTitle($fileObj->getFileName())
                        ->save(false);

                $folder->addMedia($media)->save(false);

                if($media->isImage())
                {
                    $media->createIcon();
                    $media->createMceIcon();
                    $media->createPreview();
                    
                    $parameters = m_medias_services_ParameterService::getInstance()->getParametersByFolderId($folder->getUniqueId(), $folder->getLang());

                    if(!is_null($parameters))
                    {
                        /* @var $parameter m_medias_documents_Parameter */
                        foreach($parameters as $parameter)
                        {
                            if($parameter->isGenerateOnUpload())
                            {
                                $media->advancedResizePicture($parameter->getWidth(), $parameter->getHeight(), $parameter->getCrop());
                            }
                        }
                    }
                }

                if($mediaForm == "true")
                {
                    $this->getContext()->setContext("mediaForm", $media);
                }
                else
                {
                    echo $this->getLocale("medias.locales.sendPicture");
                }
            }
            else
            {
                echo $this->getLocale("backoffice.errors.error");
            }
		} 
        else
        {
            $errors = $formProvider->getErrors();
            $errors = !empty($errors) ? $errors : $this->errors;
            echo $errors["Filedata"];
        }
	}	
	
	public function validate()
	{
		return true;//$this->getUserContext()->hasRight(array("backoffice_accessBo", "medias_Add"));
	}

    public function errorHandler()
    {
        return null;
    }

    private function isValid()
    {
        $ext = array('jpg','jpeg','gif','png','tiff','tif','zip','rar','doc','pdf','xls','xml','sit','ppt','csv','txt','rtf','docx','eps');
        foreach($ext as $a)
        {
            $ext[] = strtoupper($a);
        }

        $fileObj = f_file_File::getInstance($_FILES['Filedata']['name']);

        if(!in_array($fileObj->getExtension(), $ext))
        {
            $this->errors['Filedata'] = $this->getLocale('locale.medias.forms.filetype', null, null, $this->getLocale("medias.locales.fileExt"));
            return false;
        }

        return true;
    }

    private function fileExist($folder)
    {
        $fileArray = array();
        $savePath = $this->getDestPath($folder);

        foreach($_POST as $key => $fileName)
        {
            $value = $this->getDocumentProvider()
                    ->loadDocuments("modules_medias/media")
                    ->isChildOf($folder->getId())
                    ->whereIsEqual("document_label", $fileName)
                    ->retrieveFirstDocument();

            if (file_exists($savePath . $fileName) || !is_null($value))
            {
                $fileArray[$key] = $fileName;
            }
        }

        exit(json_encode($fileArray));
    }

    private function getDestPath($folder)
    {
        $parents = f_relation_Manager::getInstance()->getParentsIdsByDocType($folder->getUniqueId(), "modules_backoffice/folder", $folder->getLang());

        if(!is_array($parents))
        {
            $parents = array();
        }
        else
        {
            foreach($parents as $parent)
            {
                $result[] = $parent['parent_id'];
            }

            $parents = $result;
        }

        array_push($parents, $folder->getUniqueId());
        array_push($parents, strtolower($folder->getLang()));

        $parents = join(DIRECTORY_SEPARATOR, $parents);

        $destPath = HTTP_DIR.DIRECTORY_SEPARATOR."images".DIRECTORY_SEPARATOR.$parents.DIRECTORY_SEPARATOR;
        return $destPath;
    }


}